<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close @closed="$emit('closed')"
             align-center :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="160" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item :label="$t('procure.plan.name')" prop="plan_name">
                        <el-input v-model="form.plan_name" :placeholder="$t('all.enter')" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('all.remark')" prop="remark">
                        <el-input v-model="form.remark" :placeholder="$t('all.enter')" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-col :span="8">
                <el-form-item :label="$t('procure.apply.name')" prop="supplier_id">
                    <el-select v-model="form.supplier_id" :placeholder="$t('all.select')" filterable>
                        <el-option v-for="item in applyList" :key="item.id" :label="item.enterprise" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-col> -->
            <el-form-item :label="$t('procure.plan.product')" prop="purchase_detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct" v-if="mode!='turn'">{{$t ('goods.bom.select')}}</el-button>
                <sc-form-table ref="table" v-model="form.purchase_detail" :addTemplate="addTemplate" :placeholder="$t('all.noData')" height="400" hideAdd show-summary>
                    <el-table-column :label="$t('goods.goods.name')" align="center">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('goods.goods.code')" align="center">
                        <template #default="scope">
                            {{scope.row.goods_code}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('goods.goods.unit')" align="center" prop="unit_name"></el-table-column>
                    <el-table-column :label="$t('all.number')" prop="plan_num" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.plan_num" :placeholder="$t('all.number')" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.price')" prop="price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.price" :placeholder="$t('all.price')" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.subtotal')" prop="total_price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.total_price" :placeholder="$t('all.subtotal')" readonly></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.remark')" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" :placeholder="$t('all.remark')"></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-form-item :label="$t('all.attachment')" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :limit="1">
                    <el-button type="primary" icon="el-icon-upload">{{$t('all.selectattachment')}}</el-button>
                </sc-upload-file>
            </el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >{{$t('all.cancel')}}</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">{{$t('all.save')}}</el-button>
            <el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">{{$t('all.savecheck')}}</el-button>
		</template>
	</el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
	export default {
    components: { selectGoods },
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
                    add: this.$t('all.add'),
                    mrpadd: this.$t('all.add'),
                    sale: this.$t('all.add'),
                    edit: this.$t('all.edit'),
                    show: this.$t('all.show')
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
					plan_name: "",
					remark: "",
					enclosure: "",
                    purchase_detail:[],
                    is_check: 0
				},
                rules: {
					plan_name: [
						{required: true, message: this.$t('all.enter') + ' ' + this.$t('procure.plan.name')}
					],
				},
                addTemplate:{},
                dialog: {
                    goods: false,
                },
                applyList:[],
			}
		},
		mounted() {
            // this.getApply();
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(e){
                this.form.is_check = e
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res  = [];
                        if (this.form.id) {
                            res = await this.$API.procure.plan.edit.post(this.form);
                        }else{
                            res = await this.$API.procure.plan.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if(res!=''){
                            if(res.code == 1){
                                this.visible = false;
                                this.$emit('success', this.form, this.mode)
                                this.$message.success(this.$t('all.yes'))
                            }else{
                                this.$alert(res.message,this.$t('all.prompt'), {type: "error"});
                            }
                        }
                    }
                })
			},
			//表单注入数据
			async setData(data){
				this.form.id = data.id
                var res = await this.$API.procure.plan.detail.get({id:data.id});
                this.form.plan_name = res.data.plan_name
                this.form.remark = res.data.remark
                this.form.enclosure = res.data.enclosure
                let array = []
                res.data.purchase_detail.map(item=>{
                    array.push({
                        id:item.id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit && item.goods.unit.unit_name,
                        goods_code:item.goods && item.goods.goods_code,
                        plan_num:item.plan_num,
                        price:item.price,
                        total_price:item.total_price,
                        remark:item.remark,
                    })
                })
                this.form.purchase_detail = array
			},
            createSale(data){
                let array = []
                data.map(item=>{
                    array.push({
                        goods_id:item.goods_id,
                        goods_name:item.goods_name,
                        unit_name:item.unit_name,
                        goods_code:item.goods_code,
                        plan_num:item.number,
                        price:item.price,
                        total_price:Number(item.number) * Number(item.price),
                    })
                })
                this.form.purchase_detail = array
            },
            // 选择产品
            checkProduct(){
                this.dialog.goods = true
                this.$nextTick(() => {
                    this.$refs.goodsDialog.open('add')
                })
            },
            // 选择产品返回
            goodsUpdate(data){
                let array = []
                data.map((item)=>{
                    array.push({
                        goods_id:item.id,
                        goods_name:item.goods_name,
                        unit_name:item.unit&&item.unit.unit_name,
                        goods_code:item.goods_code,
                        plan_num: 1,
                        price:item.cost_price,
                        total_price:item.cost_price
                    })
                })
                let existingIds = this.form.purchase_detail.map(item => item.goods_id);
                for(let i = array.length - 1; i >= 0; i--){
                    if(existingIds.includes(array[i].goods_id)){
                        array.splice(i, 1);
                    }
                }
                this.form.purchase_detail = [...this.form.purchase_detail,...array]
            },
            // 供应商列表
            async getApply(){
                var res = await this.$API.purchase.apply.get();
                this.applyList = res.data
            },
            onFocus(event){
                event.target.select();
            },
            totalCompute() {
                this.form.purchase_detail.map(item => {
                    if(item.price && item.plan_num){
                        item.total_price = (Number(item.plan_num) * Number(item.price)).toFixed(2)
                    }
                })
            },
            saleCome(table){
                console.log('table :>> ', table);
                this.form.order_id = table.id
                let array = []
                table.product.map((item)=>{
                    array.push({
                        goods_id:item.goods_id,
                        goods_name:item.goods&&item.goods.goods_name,
                        unit_name:item.goods&&item.goods.unit&&item.goods.unit.unit_name,
                        goods_code:item.goods&&item.goods.goods_code,
                        plan_num: item.sale_num,
                        price:item.price,
                        total_price:Number(item.sale_num) * Number(item.price),
                        remark:item.remark,
                    })
                })
                this.form.purchase_detail = array
            },
		}
	}
</script>

<style>
</style>
